from __future__ import annotations
from typing import Optional
from sqlalchemy.orm import Mapped, mapped_column, relationship
from extensions import db
from datetime import datetime, date
from models.store import Store
from models.user import User
from sqlalchemy import func  # 新增导入

class Investment(db.Model):
    """投资模型"""
    __tablename__ = 'investments'

    # 投资记录唯一标识符（UUID格式）
    investment_id: Mapped[str] = mapped_column(db.String(36), primary_key=True)
    # 所属店铺ID
    store_id: Mapped[str] = mapped_column(db.String(36), db.ForeignKey('stores.store_id', ondelete='CASCADE'), nullable=False)
    # 投资人ID
    investor_id: Mapped[str] = mapped_column(db.String(36), db.ForeignKey('users.user_id', ondelete='CASCADE'), nullable=False)
    # 关联关系
    store = relationship('Store', backref='investments')
    investor = relationship('User', backref='investments')
    # 投资金额
    amount: Mapped[float] = mapped_column(db.Float, nullable=False)
    # 投资类型（如：设备投资、装修投资、其他投资等）
    type: Mapped[str] = mapped_column(db.String(20), nullable=False)
    # 投资日期
    date: Mapped[date] = mapped_column(db.Date, nullable=False)
    # 投资说明
    description: Mapped[Optional[str]] = mapped_column(db.Text)
    # 记录创建时间
    created_at: Mapped[datetime] = mapped_column(
        db.DateTime,
        server_default=func.now(),  # 优先使用数据库当前时间
        default=datetime.utcnow     # 使用Python系统时间作为后备
    )
    # 记录最后更新时间，层级信息最后一次修改的时间戳
    updated_at: Mapped[datetime] = mapped_column(
        db.DateTime,
        server_default=func.now(),  # 优先使用数据库当前时间
        default=datetime.utcnow,    # 使用Python系统时间作为后备
        onupdate=datetime.utcnow    # 更新时使用Python系统时间
    )
    def __init__(self, investment_id: str, store_id: str, investor_id: str, amount: float, type: str, 
                 date: date, description: Optional[str] = None) -> None:
        self.investment_id = investment_id
        self.store_id = store_id
        self.investor_id = investor_id
        self.amount = amount
        self.type = type
        self.date = date
        self.description = description

    def to_dict(self) -> dict:
        """将模型转换为字典"""
        return {
            'investment_id': self.investment_id,
            'store_id': self.store_id,
            'investor_id': self.investor_id,
            'amount': self.amount,
            'type': self.type,
            'date': self.date.isoformat() if self.date else None,
            'description': self.description,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'store': self.store.to_dict() if self.store else None,
            'investor': self.investor.to_dict() if self.investor else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }